package helper

import (
	"cloud-disk/core/define"
	"crypto/md5"
	"crypto/tls"
	"fmt"
	"math/rand"
	"net/smtp"
	"time"

	uuid "github.com/satori/go.uuid"

	"github.com/golang-jwt/jwt/v4"
	"github.com/jordan-wright/email"
	"golang.org/x/crypto/bcrypt"
)

func GenNewUUID() string {
	u := uuid.Must(uuid.NewV4(), nil)
	return u.String()
}

func MD5(s string) string {
	return fmt.Sprintf("%s", md5.Sum([]byte(s)))
}

func GenerateToken(id uint64, identity string, name string) (string, error) {
	uc := define.UserClaim{
		Id:       id,
		Identity: identity,
		Name:     name,
	}
	token := jwt.NewWithClaims(jwt.SigningMethodES256, uc)
	tokenString, err := token.SignedString([]byte(define.JwtKey))
	if nil != err {
		return "", err
	}
	return tokenString, nil

}

func RandomCode() string {
	s := "1234567890"
	code := ""
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < 5; i++ {
		code += string(s[rand.Intn(len(s))])
	}
	return code
}

func MailSendCode(mail string, code string) error {
	e := email.Email{}
	e.From = "<getcharzhaopan@163.com>"
	e.To = []string{mail}
	e.Subject = "Code"
	e.HTML = []byte(fmt.Sprintf("你的验证码为:%s", code))
	err := e.SendWithTLS("smtp.163.com:465", smtp.PlainAuth("", "getcharzhaopan@163.com", "", "smtp.163.com"),
		&tls.Config{InsecureSkipVerify: true, ServerName: "smtp.163.com"})
	if err != nil {
		return err
	}
	return nil
}

func HashPassword(password string) ([]byte, error) {
	return bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
}

func CheckPassword(password string, passwordHash string) error {
	return bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(password))
}
